#!/bin/bash -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
TASK_PATH=$@
TASK_MODULE=${TASK_PATH##*/}
TASK_MODULE="${TASK_MODULE%.*}"

# Ensure we are in an app dir
if [ ! -f Main.hs ]; then
    echo "You have to be in a project directory to run the script"
    exit 1
fi

FRAMEWORKDIR=$(dirname $(readlink $(which RunDevServer)))/../
if [ -d IHP ]; then
    FRAMEWORKDIR="$(pwd)/IHP"
fi

GHCI_SCRIPT="$(mktemp)"
trap "rm $GHCI_SCRIPT" EXIT

echo ":script $FRAMEWORKDIR/lib/IHP/applicationGhciConfig" > "$GHCI_SCRIPT"

if [ -d IHP ]; then
    echo ":l IHP/IHP/ScriptSupport.hs $TASK_PATH" >> "$GHCI_SCRIPT"
else
    echo "import IHP.ScriptSupport" >> "$GHCI_SCRIPT"
fi

echo "import IHP.ScriptSupport" >> "$GHCI_SCRIPT"
echo ":set -i." >> "$GHCI_SCRIPT"
echo ":l Config/Config.hs" >> "$GHCI_SCRIPT"
echo ":l Config/Config.hs Application/Script/$TASK_MODULE.hs" >> "$GHCI_SCRIPT"
echo "import qualified Application.Script.$TASK_MODULE as Script" >> "$GHCI_SCRIPT"
echo "IHP.ScriptSupport.runScript config Script.run" >> "$GHCI_SCRIPT"
echo ":quit" >> "$GHCI_SCRIPT"

ghci -package-env - -threaded -fomit-interface-pragmas +RTS -A128m -RTS < "$GHCI_SCRIPT"

